package org.xenon.vote.dao.imp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.xenon.vote.dao.StringDao;
import org.xenon.vote.model.pojo.po.Login;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class LoginDao implements StringDao<Login> {

    private final JdbcTemplate jdbcTemplate;

    public LoginDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    /**
     * 实际上是更新登录信息
     */
    @Override
    public void add(Login login) {
        if (get(login.getToken()) == null) {
            String sql = "insert into `vote`.`login` (`token`, `mail`) values (?, ?)";
            jdbcTemplate.update(sql, login.getToken(), login.getMail());
        } else
            edit(login);
    }

    @Override
    public void edit(Login login) {
        String sql = "update `vote`.`login` set `mail` = ? where `token` = ?";
        jdbcTemplate.update(sql, login.getMail(), login.getToken());
    }

    @Override
    public Login get(String token) {
        String sql = "select * from `vote`.`login` where `token` = ?";
        List<Login> list = jdbcTemplate.query(sql, new Object[]{token}, LoginRowMapper.getInstance());
        if (list.size() == 0) return null;
        return list.get(0);
    }

    @Deprecated
    @Override
    public List<Login> getAll(String id) {
        return null;
    }

    public List<Login> getAll() {
        String sql = "select * from `vote`.`login` where true";
        return jdbcTemplate.query(sql, LoginRowMapper.getInstance());
    }

    @Override
    public void del(Login login) {
        String sql = "delete FROM `vote`.`login` WHERE `mail` = ?";
        jdbcTemplate.update(sql, login.getMail());
    }


    @Override
    public void del(String mail){
        String sql = "delete FROM `vote`.`login` WHERE `mail` = ?";
        jdbcTemplate.update(sql, mail);
    }

    /**
     * 自动以RowMapper
     * 提高性能, 使用单例模式
     */
    private static class LoginRowMapper implements RowMapper<Login> {

        private static LoginRowMapper loginRowMapper;

        @Override
        public Login mapRow(ResultSet rs, int i) throws SQLException {
            return new Login(rs.getString("token"), rs.getString("mail"));
        }

        static LoginRowMapper getInstance() {
            if (loginRowMapper == null) {
                synchronized (LoginRowMapper.class) {
                    if (loginRowMapper == null) {
                        loginRowMapper = new LoginRowMapper();
                    }
                }
            }
            return loginRowMapper;
        }
    }
}
